package com.sd.projectinterface;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import objects.CSProb;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

@SuppressLint({ "ParserError", "ParserError", "ParserError", "ParserError",
		"ParserError", "ParserError", "ParserError", "ParserError",
		"ParserError", "ParserError", "ParserError", "ParserError", "ParserError", "ParserError" })
public class CreateGame extends Activity implements
		AdapterView.OnItemSelectedListener {

	private Button create;
	private Spinner subjectSpinner;
	private EditText diff, user;
	int id;
	int gameId;

	public String problemType;
	public static final String KEY_120 = "http://10.0.2.2/mathRomp/loginTest.php";
	public static final String KEY_121 = "http://10.0.2.2/mathRomp/createGame.php";

	int gramType = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_game);
		//Bundle incoming = this.getIntent().getExtras();
        //id = incoming.getInt("j");
		MyApplication myApp = (MyApplication) getApplicationContext();
        id = myApp.getId();
		problemType = "nothing";
		gameId = -1;
		create = (Button) findViewById(R.id.create_game);
		subjectSpinner = (Spinner) findViewById(R.id.select_subject);
		diff = (EditText) findViewById(R.id.difficulty);
		diff.setVisibility(8);
		user = (EditText) findViewById(R.id.competing_user);
 
		create.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if(checkUsername(user.getText()+"")){
					Intent i = new Intent(CreateGame.this, UserDNE.class);
					startActivity(i);
				}else{
					Socket s = null;
					String response = "";
					try {
						InetSocketAddress sa;
						if (gramType == 0) {
							sa = new InetSocketAddress("10.0.2.2", 8884);
						} else {
							sa = new InetSocketAddress("10.0.2.2", 8886);
						}
						s = new Socket();
						s.connect(sa, 2000);
						OutputStreamWriter osw = new OutputStreamWriter(s
								.getOutputStream());
						osw.write(problemType + "\n");
						osw.flush();
						ObjectInputStream isr = new ObjectInputStream(s
								.getInputStream());
						CSProb c = null;
						String r = "c is null";
						try {
							c = (CSProb) isr.readObject();
						} catch (ClassNotFoundException e) {
							System.out.println("c cannot be created: " + e);
							e.printStackTrace();
						}
						isr.close();
						createGame(c);
						Intent i = new Intent(CreateGame.this, ProblemView.class);
						if (c != null) {
							i.putExtra("c", c);
							i.putExtra("gameId", gameId);
							i.setData(Uri.parse(c.getProblem()));
						} else {
							i.setData(Uri.parse(r));
						}
						startActivity(i);
	
					} catch (IOException ioe) {
						Log.e("Code Error", ioe.getMessage());
					}
				}
			}
		});
		
		subjectSpinner.setOnItemSelectedListener(this);

	}

	public void onItemSelected(AdapterView<?> parent, View view, int pos,
			long id) {
		String temp = (String) parent.getItemAtPosition(pos);
		if (temp.equals("Addition")) {
			problemType = "<add>";
			gramType = 0;
		} else if (temp.equals("Subtraction")) {
			problemType = "<sub>";
			gramType = 0;
		} else if (temp.equals("Multiplication")) {
			problemType = "<mult>";
			gramType = 0;
		} else if (temp.equals("Division")) {
			problemType = "<div>";
			gramType = 0;
		} else if (temp.equals("Fraction Addition")) {
			problemType = "<fracAdd>";
			gramType = 0;
		} else if (temp.equals("Fraction Subtraction")) {
			problemType = "<fracSub>";
			gramType = 0;
		} else if (temp.equals("Fraction Multiplication")) {
			problemType = "<fracMult>";
			gramType = 0;
		} else if (temp.equals("Fraction Division")) {
			problemType = "<fracDiv>";
			gramType = 0;
		} else if (temp.equals("Exponent Addition")) {
			problemType = "<expAdd>";
			gramType = 0;
		} else if (temp.equals("Exponent Subtraction")) {
			problemType = "<expSub>";
		} else if (temp.equals("Exponent Multiplication")) {
			problemType = "<expMult>";
			gramType = 0;
		} else if (temp.equals("Exponent Division")) {
			problemType = "<expDiv>";
			gramType = 0;
		} else if (temp.equals("Associative Property")) {
			problemType = "<assoc>";
			gramType = 1;
		} else if (temp.equals("Distributive Property")) {
			problemType = "<dist>";
			gramType = 1;
		} else if (temp.equals("Factors")) {
			problemType = "<factor>";
			gramType = 1;
		} else if (temp.equals("GCF")) {
			problemType = "<gcf>";
			gramType = 1;
		} else if (temp.equals("LCM")) {
			problemType = "<lcm>";
			gramType = 1;
		} else {
			problemType = temp;
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	private boolean checkUsername(String string) {
    	InputStream is = null;
    	String result = "";
    	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    	nameValuePairs.add(new BasicNameValuePair("userName", string));
    	
    	//http post
    	try{
    		HttpClient httpclient = new DefaultHttpClient();
    		HttpPost httppost = new HttpPost(KEY_120);
    		httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    		HttpResponse response = httpclient.execute(httppost);
    		HttpEntity entity = response.getEntity();
    		is = entity.getContent();
    	}catch(Exception e){
    		Log.e("log_tag", "Error in http connection: "+e);
    	}
    	
    	//convert response to string
    	try{
    		BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"),8);
    		StringBuilder sb = new StringBuilder();
    		String line = null;
    		while((line = reader.readLine()) != null){
    			sb.append(line + "\n");
    		}
    		is.close();
    		System.out.println(result);
    		result = sb.toString();
    	}catch(Exception e){
    		Log.e("log_tag", "Error converting result: "+e);
    	}
    	
    	//parse json data
    	JSONArray jArray = null;
    	try{
    		jArray = new JSONArray(result);
    		/*for(int i=0; i<jArray.length(); i++){
    			JSONObject json_data = jArray.getJSONObject(i);
    			Log.i("log_tag","id: "+json_data.getInt("userId")+
    					", name: "+json_data.getString("username")+
    					", password: "+json_data.getString("password")+
    					", email: "+json_data.getString("email")+
    					", userType: "+json_data.getInt("userType")+
    					", totalScore: "+json_data.getInt("totalScore")
    			);
    			//Get an output to the screen
    			returnString += "\n\t" + jArray.getJSONObject(i);
    		}*/
    		
    	}catch(JSONException e){
    		Log.e("log_tag", "Error parsing data: "+e);
    	}
    	if(jArray == null){
    		return true;
    	}
		return false;
	}

	private void createGame(CSProb c){
		InputStream is = null;
    	String result = "";
    	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    	nameValuePairs.add(new BasicNameValuePair("userName", user.getText()+""));
    	nameValuePairs.add(new BasicNameValuePair("userId1", id+""));
    	System.out.println("prob: "+c.probToJson());
    	nameValuePairs.add(new BasicNameValuePair("prob", c.probToJson()));
    	nameValuePairs.add(new BasicNameValuePair("probType", problemType));
    	nameValuePairs.add(new BasicNameValuePair("gramType", gramType+""));
    	//http post
    	try{
    		HttpClient httpclient = new DefaultHttpClient();
    		HttpPost httppost = new HttpPost(KEY_121);
    		httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    		HttpResponse response = httpclient.execute(httppost);
    		HttpEntity entity = response.getEntity();
    		is = entity.getContent();
    	}catch(Exception e){
    		Log.e("log_tag", "Error in http connection: "+e);
    		return;
    	}
    	
    	//convert response to string
    	try{
    		BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"),8);
    		StringBuilder sb = new StringBuilder();
    		String line = null;
    		while((line = reader.readLine()) != null){
    			if(!line.contains("<br />") && !line.contains("Warning")){
    				sb.append(line + "\n");
    			}
    		}
    		is.close();
    		result = sb.toString();
    		System.out.println("Result: "+result);
    	}catch(Exception e){
    		Log.e("log_tag", "Error converting result: "+e);
    		return;
    	}
    	
    	//parse json data
    	JSONArray jArray = null;
    	try{
    		jArray = new JSONArray(result);
    		JSONObject json_data = jArray.getJSONObject(0);
    		/*for(int i=0; i<jArray.length(); i++){
    			JSONObject json_data = jArray.getJSONObject(i);
    			Log.i("log_tag","id: "+json_data.getInt("userId")+
    					", name: "+json_data.getString("username")+
    					", password: "+json_data.getString("password")+
    					", email: "+json_data.getString("email")+
    					", userType: "+json_data.getInt("userType")+
    					", totalScore: "+json_data.getInt("totalScore")
    			);
    			//Get an output to the screen
    			//returnString += "\n\t" + jArray.getJSONObject(i);
    		}*/
    		gameId = json_data.getInt("gameId");
    	}catch(JSONException e){
    		//mes.setText("Username not valid");
    		Log.e("log_tag", "Error parsing data: "+e);
    		return;
    	}
    	//return jObject;
	}
	
	public void onNothingSelected(AdapterView<?> arg0) {
	}
}
